import { useEffect, useState } from 'react';

import { Button, Space, Form, Row, Col, Input, Table, Select, Popconfirm } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryCouponListParams, Coupon } from './services';
import { 
  CouponStatus, queryCouponList, delCoupon, CouponInfoType, CouponCutType
} from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import GetRecordModal, { GetRecordModalProps } from './components/GetRecordModal';
import DetailModal from './components/DetailModal'
import { jump2target } from '@/utils/common';

const CouponPage: React.FC = () => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<QueryCouponListParams>()
  const [searchParams, setSearchParams] = useState<QueryCouponListParams>({
    pageNum: 1, pageSize: 10,
  })
  const couponList = useRequest(() => queryCouponList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delCouponAsync } = useRequest(delCoupon, {manual: true})
  const [getModalRecord, setGetModalRecord] = useState<GetRecordModalProps>()
  const [detailId, setDetailId] = useState<number>()

  const openEditPage = (title: string, type: string, couponId?: number) => {
    jump2target(`/coupon/couponList/edit?type=${type}&id=${couponId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/coupon/couponList/edit_title', title)
  }

  const onFinish = (formValues: QueryCouponListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const openGetModal = (record: Coupon) => {
    setGetModalRecord({
      infoId: record.id,
      infoType: record.infoType,
    })
  }

  const onGetRecordModalCancel = () => {
    setGetModalRecord(undefined)
  }

  const openDetailModal = (id: number) => {
    setDetailId(id)
  }

  const onDetailModalCancel = () => {
    setDetailId(undefined)
  }

  const columns: ColumnsType<Coupon> = [
    {
      title: '优惠券名称',
      dataIndex: 'title',
      width: 160,
    },
    {
      title: '券类型',
      dataIndex: 'infoType',
      width: 100,
      render: val => val && CouponInfoType[val],
    },
    {
      title: '优惠项目',
      dataIndex: 'cutType',
      width: 120,
      render: val => val && CouponCutType[val],
    },
    {
      title: '使用范围',
      dataIndex: 'stationType',
      width: 120,
      render: val => val === 2 ? '部分场站' : '全部自营场站',
    },
    {
      title: '领取数量',
      dataIndex: 'sendNum',
      width: 120,
      render: val => val || 0,
    },
    {
      title: '剩余数量',
      key: 'surplusNum',
      width: 120,
      render: (_, record) => {
        const { sendNum, num } = record
        if (!num) return '不限量'
        return num - (sendNum || 0)
      },
    },
    {
      title: '发放数量',
      dataIndex: 'num',
      width: 120,
      render: val => val || '不限量'
    },
    {
      title: '有效时长',
      dataIndex: 'expireDay',
      width: 120,
      render: val => `${val}天`
    },
    {
      title: '优惠内容',
      dataIndex: 'cutNum',
      width: 160,
      render: (val, record) => {
        const { infoType, fullMoney } = record
        if (infoType === CouponInfoType.折扣券) return `${val}折`
        if (fullMoney === 0) return `减${val}`
        return `满${fullMoney}元，减${val}`
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 120,
      render: val => dayjs(val).format('YYYY-MM-DD'),
    },
    {
      title: '领取截止日期',
      dataIndex: 'endTime',
      width: 140,
      render: val => val ? dayjs(val).format('YYYY-MM-DD') : '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: val => val && (CouponStatus[val] || '--'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openDetailModal(record.id)}>详情</a>
          <Access accessible={record.status === CouponStatus.上架中}>
            <Popconfirm
              title={`确定下架优惠券: ${record.title} 吗?`}
              onConfirm={() => delCouponAsync({id: record.id, status: CouponStatus.待上架}).then(couponList.refresh)}
              okText="下架"
              cancelText="取消"
            >
              <a>下架</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === CouponStatus.待上架}>
            <Popconfirm
              title={`确定删除优惠券: ${record.title} 吗?`}
              onConfirm={() => delCouponAsync({id: record.id, status: 3}).then(couponList.refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === CouponStatus.待上架}>
            <Popconfirm
              title={`确定上架优惠券: ${record.title} 吗?`}
              onConfirm={() => delCouponAsync({id: record.id, status: CouponStatus.上架中}).then(couponList.refresh)}
              okText="上架"
              cancelText="取消"
            >
              <a>上架</a>
            </Popconfirm>
          </Access>
          <a onClick={() => openGetModal(record)}>领取记录</a>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      couponList.refresh()
    }
    window.addEventListener('refreshCouponList', refresh)
    return () => {
      window.removeEventListener('refreshCouponList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加优惠券', 'edit')}>添加优惠券</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchCouponForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='券名称' name='title'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='类型' name='infoType'>
                  <Select placeholder='请选择' options={enum2options(CouponInfoType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(CouponStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={couponList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Coupon>
          rowKey='id'
          loading={couponList.loading}
          dataSource={couponList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: couponList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <GetRecordModal
        {...getModalRecord}
        onCancel={onGetRecordModalCancel}
      />
      <DetailModal
       id={detailId}
       onCancel={onDetailModalCancel}
      />
    </div>
  );
};

export default CouponPage;
